package com.itheima.controller;

import com.itheima.pojo.Result;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
public class UploadController {

    @PostMapping("/upload")
    public Result uploads(String name, Integer age, MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return Result.error("请上传文件");
        }

        // 2. 使用try-with-resources自动关闭资源
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            // 3. 安全获取第二个Sheet（避免索引越界）
            Sheet sheet = workbook.getSheetAt(1);  // 改用索引1获取第一个Sheet

            List<List<String>> excelData = new ArrayList<>();

            // 4. 遍历行（跳过空行）
            for (Row row : sheet) {
                List<String> rowData = new ArrayList<>();

                // 5. 遍历单元格（处理空单元格）
                for (int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) {
                    Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    rowData.add(getCellValueAsString(cell));  // 使用自定义方法读取值
                }
                excelData.add(rowData);
            }

            // 6. 返回解析数据
            return Result.success(excelData);
        }
    }

    // 7. 正确处理各种单元格类型
    private String getCellValueAsString(Cell cell) {
        if (cell == null) return "";

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getLocalDateTimeCellValue().toString();
                }
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}
